﻿//===============================================================================
// Microsoft Innovation Centre - Western Europe
// Copyright (c) 2008 Microsoft Corporation. All rights reserved.
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//===============================================================================
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious.  No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
//===============================================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace Microsoft.WVB.Silverlight.Infrastructure
{
    //Extension methods for symbol syntax in c#
    public static class SymbolExtensions
    {
        //Ref.: http://themechanicalbride.blogspot.com/2007/03/symbols-on-steroids-in-c.html
        public static string GetPropertySymbol<T, R>(this T o, Expression<Func<T, R>> expr)
        {
            var outerMostMemberExpression = (MemberExpression)(((LambdaExpression)(expr)).Body);
            var memberExpressions =
                Iterate<MemberExpression>(x => x.Expression as MemberExpression, outerMostMemberExpression)
                .TakeWhile(x => x != null)
                .Aggregate<MemberExpression, string>(String.Empty, (left, right) => right.Member.Name + "." + left);
            return memberExpressions.Substring(0, memberExpressions.Length - 1);
        }
        public static IEnumerable<T> Iterate<T>(Func<T, T> f, T initial)
        {
            var value = initial;
            while (true)
            {
                yield return value;
                value = f(value);
            }
        }
    }
}
